package com.xbq.exceleditor.ui.filechooser

import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.xbq.exceleditor.databinding.FragmentStorageFileBinding
import com.xbq.exceleditor.ui.filechooser.media.FileTypeEnum
import com.xbq.xbqsdk.component.activity.VBFragment
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.FileFilter

/**
 * Author: liaohaiping
 * Time: 2021-07-01
 * Description:
 */
@AndroidEntryPoint
class StorageFileFragment :
    VBFragment<FragmentStorageFileBinding>() {
    var currentDir: File? = null
    val rootdir by lazy { Environment.getExternalStorageDirectory() }
    private val adapter by lazy { FileAdapter() }
    private var fileType: FileTypeEnum? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        parseArguments()
        binding.fileList.adapter = adapter
        binding.fileList.layoutManager = LinearLayoutManager(requireContext())
        adapter.setOnItemClickListener { adt, view, position ->
            val item = adapter.getItem(position)
            if (item.isDirectory) {
                LogUtils.d(item.absolutePath)
                listChildFiles(item)
            } else {
                adapter.selectFile(item)
                EventBus.getDefault().post(item)
            }
        }

        binding.btnBackParentDir.setOnClickListener {
            currentDir?.parentFile?.let {
                LogUtils.d(it.absolutePath)
                listChildFiles(it)
            }
        }

        listChildFiles(rootdir)

    }

    private fun parseArguments() {
        arguments?.let {
            val fileTypeName = it.getString(FileByExtensionListFragment.EXTRA_FILE_TYPE)
            fileType = FileTypeEnum.valueOf(fileTypeName!!)
        }
    }

    fun listChildFiles(parentDir: File) {
        val dirs = parentDir.listFiles(DirectoryFilter())
        val xlsx = parentDir.listFiles(FileTypeFilter(fileType))
        val results = dirs?.asList()?.toMutableList()?:mutableListOf()
        xlsx?.let { results.addAll(it) }
        adapter.setList(results)
        currentDir = parentDir
        binding.btnBackParentDir.visibility = if (currentDir == rootdir) View.GONE else View.VISIBLE
        binding.tvCurrentDirctory.text =
            parentDir.absolutePath.replace(rootdir.absolutePath, "手机存储")
    }


    class DirectoryFilter : FileFilter {
        override fun accept(pathname: File?): Boolean {
            return pathname?.isDirectory == true
        }
    }

    class FileTypeFilter(val fileType: FileTypeEnum?) : FileFilter {
        override fun accept(pathname: File?): Boolean {
            return pathname?.isFile == true && (fileType == null || fileType.fileExtensions.contains(
                pathname!!.extension
            ))
        }
    }

    companion object {
        const val EXTRA_FILE_TYPE = "EXTRA_FILE_TYPE"
        const val EXTRA_DIR_TYPE = "EXTRA_DIR_TYPE"
        const val DIR_TYPE_WEIXIN = 100
        const val DIR_TYPE_QQ = 200

        fun newFragment(
            fileType: FileTypeEnum
        ): StorageFileFragment {
            return StorageFileFragment().apply {
                val args = Bundle()
                args.putString(EXTRA_FILE_TYPE, fileType.name)
                arguments = args
            }
        }
    }
}